<template>
  <h2>当前求和为：{{ sum }}</h2>
  <button @click="sum++">sum+1</button>
  <hr>
  <h2>{{ msg }}</h2>
  <button @click="msg+='!'">改变msg</button>
  <hr>
  <h2>姓名：{{person.name}}</h2>
  <h2>年龄：{{person.age}}</h2>
  <h2>薪资：{{person.jobs.j1.salary}}K</h2>
  <button @click="person.name+='~'">修改姓名</button>
  <button @click="person.age++">增长年龄</button>
  <button @click="person.jobs.j1.salary++">增长薪资</button>
</template>

<script>
import {reactive, ref, watch} from "vue";

export default {
  name: "Demo",
  components: {},
  props: [],
  emits: [], // 用于注册VC的自定义事件，可不写，但会报警
  // region Vue2写法
  /*watch: {
    /!*'sum'(valNew, valOld){
      console.log('sum的值变化了', valNew, valOld);
    }*!/
    'sum': {
        immediate: false,
        deep:true,
        handler(valNew, valOld){
          console.log('sum的值变化了', valNew, valOld);
        }
    }
  },*/
  // endregion
  setup() {
    let sum = ref(0);
    let msg = ref('Hello');
    let person = reactive({
      name: '张三',
      age: 18,
      jobs:{
        j1:{
          salary:20
        }
      }
    });

    //1.监视单个ref数据
    /*watch(sum, (newVal, oldVal) => {
      console.log('sum变化了', newVal, oldVal);
    });*/

    //2.监视多个ref数据
    watch([sum, msg], (newVal, oldVal) => {
      console.log('sum或msg变化了', newVal, oldVal);
    }, {immediate: true, deep: true});

    /*3.监视reactive数据的全部属性
     注意：
       1.此处无法正确地获得oldVal；
       2.强制开启了深度监视（deep配置无效）*/
    // watch(person, (newVal, oldVal) => {
    //   console.log('person变化了', newVal, oldVal);
    // },{immediate: true, deep: true});

    //解决方法：(要先将person中要监视的属性单独拿出来用ref来声明，再用watch监视)

    //4.监视reactive数据的某个属性
    // watch(() => {
    //   return person.age;
    // }, (newVal, oldVal) => {
    //   console.log('person的age变化了', newVal, oldVal);
    // },{immediate: true, deep: true});

    //5.监视reactive数据的多个属性
    // watch([() => person.age, () => person.name], (newVal, oldVal) => {
    //   console.log('person的age或name或jobs变化了', newVal, oldVal);
    // },{immediate: true, deep: true});

    //6.监视reactive数据的多个属性（属性为对象，需要开启deep）
    // watch(() => person.jobs, (newVal, oldVal) => {
    //   console.log('person的jobs变化了', newVal, oldVal);
    // },{immediate: true, deep: true});

    return {
      sum,
      msg,
      person
    }
  },
}
</script>

<style scoped>

</style>